package com.bw.service.impl;

import com.bw.domain.Role;
import com.bw.domain.User;
import com.bw.domain.UserMoney;
import com.bw.mapper.UserMapper;
import com.bw.service.UserService;
import com.bw.utils.MyEx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author bobo棒
 * @date 2025年02月21日 11:46
 */

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User selectByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public List<User> list(User user) {
        return userMapper.list(user);
    }

    @Override
    public User get(String id) {
        return userMapper.get(id);
    }

    @Override
    public List<Role> listRole() {
        return userMapper.listRole();
    }

    @Override
    public int update(User user) {


        //修改用户信息
      int i=  userMapper.update(user);
      //修改用户角色
        //先删除中间表
        userMapper.deleteUserRole(user.getId()) ;
        //后增加
        String roleIds = user.getRoleIds();
        String[] split = roleIds.split(",");
        for (int j = 0; j < split.length; j++) {
            userMapper.insertUserRole(user.getId(),split[j]);
        }
      //  int x=10/0;
        return i;
    }

    @Override
    public List<Role> listRoleByUserId(String id) {
        return userMapper.listRoleByUserId(id);
    }


    //为该方法,增加事务的特性-并标记出现异常则事务回滚

    @Transactional(rollbackFor = MyEx.class)
    @Override
    public boolean recharge(UserMoney userMoney) throws MyEx {
        //尝试充值
        try {
            //1.更改用户账户余额
            userMapper.updateBalance(userMoney);

           int i=1/0;//测试事务回滚
            //2.增加充值流水
            userMapper.insertRecharge(userMoney);
            return true;
        }catch (Exception e){
         e.printStackTrace();
         //抛出异常.事务回滚
         throw new MyEx("充值失败:"+e.getMessage());

        }
    }

    @Override
    public List<UserMoney> listRecharge(UserMoney userMoney) {
        return userMapper.listRecharge(userMoney);
    }

    @Override
    public int updateStatus(User user) {
        return userMapper.updateStatus(user);
    }

    @Override
    public List<User> listByIds(String ids) {
        return userMapper.listByIds(ids);
    }
}
